package com.cicadasmall.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cicadasmall.common.exception.ServiceException;
import com.cicadasmall.common.resp.R;
import com.cicadasmall.system.dto.DictInputDTO;
import com.cicadasmall.system.dto.DictQueryDTO;
import com.cicadasmall.system.dto.DictUpdateDTO;
import com.cicadasmall.data.domain.DictDO;
import com.cicadasmall.system.manager.DictManager;
import com.cicadasmall.system.service.IDictService;
import com.cicadasmall.system.vo.DictDetailsVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


@Api(tags = "S-字典管理接口")
@RestController
@RequestMapping("/system/dict")
public class DictController {
    @Autowired
    private IDictService dictService;

    @ApiOperation(value = "字典列表接口")
    @GetMapping("/list")
    public R<List<DictDO>> getList(DictQueryDTO dictQueryDTO) {
        return dictService.findList(dictQueryDTO);
    }

    @ApiOperation(value = "字典列表接口")
    @GetMapping("/data/{dictCode}")
    public R<List<DictDetailsVo>> data(@PathVariable String dictCode) {
        return R.ok(DictManager.getOptionalByDictCode(dictCode)
                .orElseThrow(new ServiceException("字典[" + dictCode + "]不存在！"))
                .stream()
                .map(dict -> {
                    DictDetailsVo dictDetailsVo = new DictDetailsVo();
                    dictDetailsVo.setName(dict.getDictName());
                    dictDetailsVo.setValue(dict.getDictValue());
                    return dictDetailsVo;
                }).collect(Collectors.toList()));
    }

    @ApiOperation(value = "字典列表接口")
    @GetMapping("/page")
    public R<Page<DictDO>> getPage(DictQueryDTO dictQueryDTO) {
        return dictService.page(dictQueryDTO);
    }

    @ApiOperation(value = "字典保存接口")
    @PostMapping
    public R<Boolean> save(@RequestBody @Valid DictInputDTO dictInputDTO) {
        return dictService.save(dictInputDTO);
    }

    @ApiOperation(value = "字典更新接口")
    @PutMapping
    public R<Boolean> updateById(@RequestBody @Valid DictUpdateDTO dictUpdateDTO) {
        return dictService.update(dictUpdateDTO);
    }

    @ApiOperation(value = "字典详情接口")
    @GetMapping("/{id}")
    public R<DictDO> getById(@PathVariable Long id) {
        return dictService.findById(id);
    }

    @ApiOperation(value = "字典删除接口")
    @DeleteMapping("/{id}")
    public R<Boolean> removeById(@PathVariable Long id) {
        return dictService.deleteById(id);
    }


}